package com.zy.fee.roadpark.activity.nb;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.printer.sdk.Barcode;
import com.printer.sdk.PrinterConstants;
import com.spd.print.jx.impl.PrintImpl;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.app.AppApplication;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.CommonLogic;
import com.zy.fee.roadpark.dao.FileLogic;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordList;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.config.LibraryConstants;
import com.zygk.library.model.CommonResult;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.FileUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.ListUtils;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.LibraryCommonDialog;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.printer.sdk.PrinterConstants.BarcodeType.DATAMATRIX;
import static com.printer.sdk.PrinterConstants.BarcodeType.PDF417;

/**
 * @author: wikison
 * @date: 2021/4/23
 */
public class NbForensicsAddActivity extends BaseActivity {
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.view) View view;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;

  private ArrayList<ImageItem> images = null;
  private String carPath = "";
  private M_NodeRecord nodeRecord;
  private String code, plateNumber, pic;
  private String recordID = "", newRecordID = "";
  private int iPicType = 0;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_forensics_add);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    initImagePickerSingle(false);

    nodeRecord =
        (M_NodeRecord) getIntent().getSerializableExtra(
            NbNodeReceivablesActivity.INTENT_NODE_RECORD);

    recordID = nodeRecord.getNodeRecordID();
    code = nodeRecord.getCode();
  }

  private void initView() {
    lhTvTitle.setText("取证");

    etCode.setText(code);
    etCode.setEnabled(false);
    gpvPlateNumber.setPassword("");
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 2 && position <= 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    view.setOnClickListener(v -> viewKeyboard.setVisibility(View.GONE));

    gpvPlateNumber.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      }
    });
  }

  /**
   * 车牌识别
   */
  private void ocr_vehicle_plate(String path) {
    FileLogic.GetCPSB(mContext, path, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        String plateNum = (String) obj;
        if (!StringUtils.isBlank(plateNum) && (plateNum.length() == 7 || plateNum.length() == 8)) {
          gpvPlateNumber.setPassword(plateNum);

          FileUtil.deleteSingleFile(path);
          FileUtil.deletePicture(mContext, path);
        } else {
          ToastUtil.showMessage(mContext, "识别出的车牌号有误");
        }
      }

      @Override public void onFailed() {
        ToastUtil.showMessage(mContext, "识别失败，请重新识别或手动输入");
      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);

        if (iPicType == 0) {
          String path = images.get(0).path;
          ocr_vehicle_plate(path);
        } else if (iPicType == 1) {
          String originImage = images.get(0).path;
          FileInputStream fis = null;
          try {
            fis = new FileInputStream(originImage);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);

            if (null == bitmap) {
            } else {
              if (addWatermarkBitmap(bitmap, DateTimeUtil.getCurrentTime(), bitmap.getWidth(),
                  bitmap.getHeight())) {
              } else {
                ToastUtil.showMessage(mContext, "水印添加失败");
                carPath = originImage;
              }
            }
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  private boolean addWatermarkBitmap(Bitmap bitmap, String strMark, int w, int h) {
    int destWidth = w;   //此处的bitmap已经限定好宽高
    int destHeight = h;

    Bitmap carBitmap =
        Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888); //定好宽高的全彩bitmap
    Canvas canvas = new Canvas(carBitmap);//初始化画布绘制的图像到icon上

    Paint photoPaint = new Paint(); //建立画笔
    photoPaint.setDither(true); //获取跟清晰的图像采样
    photoPaint.setFilterBitmap(true);//过滤一些

    Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());//创建一个指定的新矩形的坐标
    Rect dst = new Rect(0, 0, destWidth, destHeight);//创建一个指定的新矩形的坐标
    canvas.drawBitmap(bitmap, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
    textPaint.setTextSize(destWidth / 20);//字体大小
    textPaint.setTextAlign(Paint.Align.CENTER);
    textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
    textPaint.setAntiAlias(true);  //抗锯齿
    textPaint.setStrokeWidth(3);
    textPaint.setAlpha(15);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(Color.RED);//水印文字颜色
    textPaint.setShadowLayer(1f, 0f, 3f, Color.LTGRAY);
    canvas.drawText(strMark, destWidth / 3, 100, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
    canvas.save();
    canvas.restore();
    bitmap.recycle();

    carPath = LibraryConstants.SAVE_IMAGE_PATH_IMGS + DateTimeUtil.getCurrentTime() + ".jpg";
    imageManager.loadLocalImage(carPath, ivPhoto);

    try {
      ImageUtil.saveImage(carBitmap, carPath); //保存至文件
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  private void uploadPic() {
    String fileName = UUID.randomUUID().toString() + carPath.substring(carPath.lastIndexOf("."));

    CommonLogic.do_upload_pic(mContext, true, carPath, fileName, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        CommonResult result = (CommonResult) obj;
        pic = result.getData();
        node_refresh();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {

      }
    });
  }

  private void node_refresh() {
    NbNodeRecordLogic.nbnode_record_refresh(mContext, nodeRecord.getNodeRecordID(), plateNumber,
        pic,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {

          }

          @Override public void onSucceed(Object obj) {
            CommonResult result = (CommonResult) obj;
            newRecordID = result.getNodeRecordID();

            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            sendBroadcast(new Intent(Constants.BROADCAST_FORENSICS_SUCCESS));
            ToastUtil.showMessage(mContext, "提交成功");

            //打印小票, 打印完成后追缴
            printTicket();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void record_no_pay_list() {
    NbNodeRecordLogic.nbnode_record_unpay_list(mContext, plateNumber, 1, Constants.ROWS,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordList result = (APIM_NodeRecordList) obj;
            if (ListUtils.isEmpty(result.getNodeRecordList())) {
              finish();
            } else {
              if (hasRecordList(result.getNodeRecordList())) {
                LibraryCommonDialog.showYesOrNoDialog(mContext, "追缴提示", plateNumber + "有历史未缴费单据需追缴",
                    "取消", "进入追缴页面", () -> {
                      Intent intent = new Intent(mContext, NbOverpayBillListActivity.class);
                      intent.putExtra(NbOverpayBillListActivity.INTENT_PLATE_NUMBER, plateNumber);
                      startActivity(intent);
                      finish();
                    }, () -> {
                      finish();
                    });
              } else {
                finish();
              }
            }
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void printTicket() {
    try {
      PrintImpl mPrinter = AppApplication.getPrinterImpl();
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      mPrinter.printText("临停缴费信息单");
      mPrinter.setPrinter(1, 1);

      mPrinter.setPrinter(2, 0);

      StringBuilder sb = new StringBuilder();
      sb.append(
          "所在停车场: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_NAME));
      sb.append("\n");
      sb.append("所停车位:   " + code);
      sb.append("\n");
      sb.append(
          "所停时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      sb.append(
          "取证人编码: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.USER_NAME));
      sb.append("\n");
      sb.append("取证时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      sb.append("收款单位:   " + "尚盈车联");
      sb.append("\n");
      sb.append("客服电话:   " + AppApplication.instance().parkTelephone);
      sb.append("\n");
      sb.append("此路段全程电子监控，请自觉缴费！");
      sb.append("\n");
      sb.append("恶意逃费行为将被计入好享泊个人诚信系统，后期对您的停车权益产生影响。");
      sb.append("\n");
      sb.append("付费完成请在3分钟内驶离，否则重新计费！");
      sb.append("\n");
      sb.append("温馨提示: 本停车位收取的费用为车位使用费，不含车辆保管费用，勿将贵重物品遗留在车上，请随身携带，谨防被盗，谢谢合作！");
      sb.append("\n");
      sb.append("现金支付用户请向收费员索要打印小票并妥善保管。");
      sb.append("\n");
      sb.append("如需停车发票请联系客服。");
      sb.append("\n");
      sb.append("\n");
      // 字号使用默认
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);
      // 打印
      mPrinter.printText(sb.toString());

      // 二维码图片
      String url = Constants.PAY_NB_URL + newRecordID;

      Barcode barcode;
      int[] width = new int[] { 0, 1, 0 };
      int[] height = new int[] { 76, 0, 8 };
      byte[] bytes = new byte[] { PrinterConstants.BarcodeType.QRCODE, PDF417, DATAMATRIX };
      barcode = new Barcode(bytes[0], width[0], height[0], 6, url);
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.printBarCode(barcode);
      mPrinter.setPrinter(1, 1);

      sb = new StringBuilder();
      sb.append("微信扫码自助缴费");
      sb.append("\n");
      sb.append("\n");
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.printText(sb.toString());

      sb = new StringBuilder();
      sb.append("" + plateNumber);
      sb.append("\n");
      sb.append("\n");
      sb.append("\n");

      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      mPrinter.printText(sb.toString());
      mPrinter.setPrinter(1, 2);

      //打印完成后查询追缴
      record_no_pay_list();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private boolean hasRecordList(List<M_NodeRecord> nodeRecordList) {
    boolean result = false;
    for (int i = 0; i < nodeRecordList.size(); i++) {
      if (nodeRecordList.get(i).getState() == 1) {
        result = true;
        break;
      }
    }
    return result;
  }

  @OnClick({
      R.id.ll_back, R.id.ll_right, R.id.iv_scan, R.id.iv_photo, R.id.tv_button
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_scan:
        viewKeyboard.setVisibility(View.GONE);
        iPicType = 0;
        picOne();
        break;
      case R.id.iv_photo:
        viewKeyboard.setVisibility(View.GONE);
        iPicType = 1;
        picOne();
        break;
      case R.id.tv_button:
        plateNumber = gpvPlateNumber.getPassWord();
        if (!StringUtils.isBlank(plateNumber)) {
          if (!StringUtils.isBlank(carPath)) {
            showCommitDialog();
          } else {
            if (!StringUtils.isBlank(pic)) {
              showCommitDialog();
            } else {
              ToastUtil.showMessage(mContext, "请上传图片");
            }
          }
        } else {
          ToastUtil.showMessage(mContext, "请输入车位号和车牌号");
        }
        break;
    }
  }

  private void showCommitDialog() {
    LibraryCommonDialog.showYesOrNoDialog(mContext, "", "确认提交", "取消", "确认", () -> {
      if (!StringUtils.isBlank(carPath)) {
        //上传图片后
        uploadPic();
      } else {
        node_refresh();
      }
    }, () -> {

    });
  }
}
